package com.cali.libcore.dialog.manager

import android.app.Activity
import android.content.Context
import android.graphics.Point
import android.os.Build
import android.view.KeyCharacterMap
import android.view.KeyEvent
import android.view.ViewConfiguration

object ScreenUtil {


    private val point = Point()


    fun dp2px(context: Context, dpValue: Float): Int {
        return (context.resources.displayMetrics.density.toInt().toFloat() * dpValue + 0.5f).toInt()
    }

    fun sp2px(context: Context, spValue: Float): Int {
        val fontScale = context.resources.displayMetrics.scaledDensity
        return (spValue * fontScale + 0.5f).toInt()
    }

    /**
     * 获取屏幕宽度
     *
     * @param activity Activity
     * @return ScreenWidth
     */
    fun getScreenWidth(activity: Activity): Int {
        val display = activity.windowManager.defaultDisplay
        if (display != null) {
            display.getSize(point)
            return point.x
        }
        return 0
    }

    /**
     * 获取屏幕高度
     *
     * @param activity Activity
     * @return ScreenHeight
     */
    fun getScreenHeight(activity: Activity): Int {
        val display = activity.windowManager.defaultDisplay
        if (display != null) {
            display.getSize(point)
            return point.y - getStatusBarHeight(activity)
        }
        return 0
    }

    /**
     * 计算statusBar高度
     *
     * @param activity Activity
     * @return statusBar高度
     */
    private fun getStatusBarHeight(activity: Activity): Int {
        val resources = activity.resources
        val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
        return resources.getDimensionPixelSize(resourceId)
    }

    /**
     * 计算navigationBar高度
     *
     * @param activity navigationBar高度
     * @return navigationBar高度
     */
    fun getNavigationBarHeight(activity: Activity): Int {
        val resources = activity.resources
        val resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android")
        return resources.getDimensionPixelSize(resourceId)
    }


    fun isNavigationBarShow(activity: Activity): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            val display = activity.windowManager.defaultDisplay
            val size = Point()
            val realSize = Point()
            display.getSize(size)
            display.getRealSize(realSize)
            return realSize.y != size.y
        } else {
            val menu = ViewConfiguration.get(activity).hasPermanentMenuKey()
            val back = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK)
            return !(menu || back)
        }
    }
}
